package cn.axj.crypt.secret.implement;

import cn.axj.crypt.constant.AlgorithmConstant;
import cn.axj.crypt.secret.BaseAlgorithmHttpInputMessage;
import cn.axj.crypt.secret.config.RsaKeyConfig;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author aoxiaojun
 * @date 2020/12/11 15:30
 **/
@Component
public class RsaAlgorithmHttpInputMessage extends BaseAlgorithmHttpInputMessage {

    @Resource
    private RsaKeyConfig rsaKeyConfig;


    @Override
    public String getBinding() {
        return AlgorithmConstant.RSA;
    }

    @Override
    public String decrypt(String content) throws Exception {
        return decode(content);
    }

    @Override
    public String encrypt(String content) throws Exception {
        return this.encrypt(content,getPublicKey());
    }


    private static final String KEY_ALGORTHM = "RSA";
    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
    private static final String DEFAULT_CHARSET = "UTF-8";

    private static String publicKeyStr;
    private static String privateKeyStr;

    @Autowired
    public void setPublicKeyStr() {
        RsaAlgorithmHttpInputMessage.publicKeyStr = rsaKeyConfig.getPublicKey();
    }

    @Autowired
    public void setPrivateKeyStr() {
        RsaAlgorithmHttpInputMessage.privateKeyStr = rsaKeyConfig.getPrivateKey();
    }

    /**
     * 分段加密
     * @param content
     * @param publicKey
     * @return
     * @throws Exception
     */
    private String encrypt(String content, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("rsa");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        Base64 base64 = new Base64();
        byte[] data = content.getBytes();
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        for(int i = 0; inputLen - offSet > 0; offSet = i * 117) {
            byte[] cache;
            if(inputLen - offSet > 117) {
                cache = cipher.doFinal(data, offSet, 117);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            ++i;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return base64.encodeToString(encryptedData);
    }

    /**
     * 分段解密
     * @param content
     * @param privateKey
     * @return
     * @throws Exception
     */
    private String decrypt(String content, PrivateKey privateKey) throws Exception {
        byte[] byteArray = Base64.decodeBase64(content);
        Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        int inputLen = byteArray.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        for(int i = 0; inputLen - offSet > 0; offSet = i * 128) {
            byte[] cache;
            if(inputLen - offSet > 128) {
                cache = cipher.doFinal(byteArray, offSet, 128);
            } else {
                cache = cipher.doFinal(byteArray, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            ++i;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return new String(decryptedData);

    }

    private PrivateKey getPrivateKey() throws Exception {
        byte[] keyBytes = decryptBase64(RsaAlgorithmHttpInputMessage.privateKeyStr);
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
        return keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    }

    private PublicKey getPublicKey() throws Exception {
        byte[] keyBytes = decryptBase64(RsaAlgorithmHttpInputMessage.publicKeyStr);
        //构造X509EncodedKeySpec对象
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        //指定加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
        return keyFactory.generatePublic(x509EncodedKeySpec);
    }

    private byte[] decryptBase64(String keys) {
        Base64 base64 = new Base64();
        return base64.decode(keys);
    }

    public  String encode(String content) throws Exception {
        return encrypt(content, getPublicKey());
    }

    public String decode(String content) throws Exception {
        return decrypt(content, getPrivateKey());
    }


}
